<template>
  <div class="host-group-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>主机组管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加主机组
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="组名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入组名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="环境">
            <el-select
              v-model="searchForm.environment"
              placeholder="请选择环境"
              clearable
              style="width: 120px"
            >
              <el-option
                v-for="env in environmentOptions"
                :key="env.code"
                :label="env.name"
                :value="env.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="正常" value="normal" />
              <el-option label="维护中" value="maintenance" />
              <el-option label="停用" value="disabled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 主机组表格 -->
      <el-table
        :data="hostGroupList"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="组名称" min-width="150" />
        <el-table-column prop="code" label="组代码" width="120" />
        <el-table-column prop="environment" label="环境" width="100">
          <template #default="{ row }">
            <el-tag :type="getEnvironmentTagType(row.environment)">
              {{ getEnvironmentName(row.environment) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="组类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hostCount" label="主机数量" width="100">
          <template #default="{ row }">
            <el-button 
              type="text" 
              @click="showHostList(row)"
              :disabled="row.hostCount === 0"
            >
              {{ row.hostCount }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="loadBalancer" label="负载均衡" width="120">
          <template #default="{ row }">
            <el-switch
              v-model="row.loadBalancer.enabled"
              @change="handleLoadBalancerChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="healthCheck" label="健康检查" width="120">
          <template #default="{ row }">
            <el-switch
              v-model="row.healthCheck.enabled"
              @change="handleHealthCheckChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="showDetailDialog(row)"
            >
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="showEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="manageHosts(row)"
            >
              管理主机
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :disabled="row.hostCount > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑主机组对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="组名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入组名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组代码" prop="code">
              <el-input v-model="form.code" placeholder="请输入组代码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="环境" prop="environment">
              <el-select v-model="form.environment" placeholder="请选择环境" style="width: 100%">
                <el-option
                  v-for="env in environmentOptions"
                  :key="env.code"
                  :label="env.name"
                  :value="env.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择组类型" style="width: 100%">
                <el-option label="Web服务器组" value="web" />
                <el-option label="数据库服务器组" value="database" />
                <el-option label="缓存服务器组" value="cache" />
                <el-option label="消息队列组" value="mq" />
                <el-option label="文件服务器组" value="file" />
                <el-option label="监控服务器组" value="monitor" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 负载均衡配置 -->
        <el-form-item label="负载均衡">
          <el-switch v-model="form.loadBalancer.enabled" />
          <div v-if="form.loadBalancer.enabled" style="margin-top: 10px;">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="算法" prop="loadBalancer.algorithm">
                  <el-select v-model="form.loadBalancer.algorithm" style="width: 100%">
                    <el-option label="轮询" value="round_robin" />
                    <el-option label="加权轮询" value="weighted_round_robin" />
                    <el-option label="最少连接" value="least_connections" />
                    <el-option label="IP哈希" value="ip_hash" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="端口" prop="loadBalancer.port">
                  <el-input-number v-model="form.loadBalancer.port" :min="1" :max="65535" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
        
        <!-- 健康检查配置 -->
        <el-form-item label="健康检查">
          <el-switch v-model="form.healthCheck.enabled" />
          <div v-if="form.healthCheck.enabled" style="margin-top: 10px;">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="检查间隔(秒)" prop="healthCheck.interval">
                  <el-input-number v-model="form.healthCheck.interval" :min="5" :max="300" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="超时时间(秒)" prop="healthCheck.timeout">
                  <el-input-number v-model="form.healthCheck.timeout" :min="1" :max="60" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="失败阈值" prop="healthCheck.failureThreshold">
                  <el-input-number v-model="form.healthCheck.failureThreshold" :min="1" :max="10" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="检查路径" prop="healthCheck.path">
              <el-input v-model="form.healthCheck.path" placeholder="如: /health" />
            </el-form-item>
          </div>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="normal">正常</el-radio>
            <el-radio value="maintenance">维护中</el-radio>
            <el-radio value="disabled">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入主机组描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 主机组详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="主机组详情"
      width="1000px"
    >
      <div class="detail-content" v-if="currentHostGroup">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="组名称">
            {{ currentHostGroup.name }}
          </el-descriptions-item>
          <el-descriptions-item label="组代码">
            {{ currentHostGroup.code }}
          </el-descriptions-item>
          <el-descriptions-item label="环境">
            <el-tag :type="getEnvironmentTagType(currentHostGroup.environment)">
              {{ getEnvironmentName(currentHostGroup.environment) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="组类型">
            <el-tag :type="getTypeTagType(currentHostGroup.type)">
              {{ getTypeLabel(currentHostGroup.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentHostGroup.status)">
              {{ getStatusLabel(currentHostGroup.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="主机数量">
            {{ currentHostGroup.hostCount }}
          </el-descriptions-item>
          <el-descriptions-item label="负载均衡">
            {{ currentHostGroup.loadBalancer.enabled ? '已启用' : '未启用' }}
          </el-descriptions-item>
          <el-descriptions-item label="健康检查">
            {{ currentHostGroup.healthCheck.enabled ? '已启用' : '未启用' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" span="2">
            {{ currentHostGroup.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="描述" span="2">
            {{ currentHostGroup.description }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 负载均衡详情 -->
        <div v-if="currentHostGroup.loadBalancer.enabled" style="margin-top: 20px;">
          <h4>负载均衡配置</h4>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="算法">
              {{ currentHostGroup.loadBalancer.algorithm }}
            </el-descriptions-item>
            <el-descriptions-item label="端口">
              {{ currentHostGroup.loadBalancer.port }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 健康检查详情 -->
        <div v-if="currentHostGroup.healthCheck.enabled" style="margin-top: 20px;">
          <h4>健康检查配置</h4>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="检查间隔">
              {{ currentHostGroup.healthCheck.interval }}秒
            </el-descriptions-item>
            <el-descriptions-item label="超时时间">
              {{ currentHostGroup.healthCheck.timeout }}秒
            </el-descriptions-item>
            <el-descriptions-item label="失败阈值">
              {{ currentHostGroup.healthCheck.failureThreshold }}次
            </el-descriptions-item>
            <el-descriptions-item label="检查路径" span="3">
              {{ currentHostGroup.healthCheck.path }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search
} from '@element-plus/icons-vue'

// 注册图标组件
const iconComponents = {
  Plus,
  Search
}

// 接口定义
interface HostGroup {
  id: string
  name: string
  code: string
  environment: string
  type: string
  status: string
  hostCount: number
  loadBalancer: {
    enabled: boolean
    algorithm: string
    port: number
  }
  healthCheck: {
    enabled: boolean
    interval: number
    timeout: number
    failureThreshold: number
    path: string
  }
  description: string
  createTime: string
}

interface SearchForm {
  name: string
  environment: string
  status: string
}

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('添加主机组')
const isEdit = ref(false)
const currentHostGroup = ref<HostGroup | null>(null)

// 搜索表单
const searchForm = reactive<SearchForm>({
  name: '',
  environment: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 主机组列表
const hostGroupList = ref<HostGroup[]>([])

// 表单数据
const form = reactive<HostGroup>({
  id: '',
  name: '',
  code: '',
  environment: '',
  type: '',
  status: 'normal',
  hostCount: 0,
  loadBalancer: {
    enabled: false,
    algorithm: 'round_robin',
    port: 80
  },
  healthCheck: {
    enabled: false,
    interval: 30,
    timeout: 5,
    failureThreshold: 3,
    path: '/health'
  },
  description: '',
  createTime: ''
})

// 表单引用
const formRef = ref()

// 选项数据
const environmentOptions = ref([
  { code: 'prod', name: '生产环境' },
  { code: 'test', name: '测试环境' },
  { code: 'dev', name: '开发环境' }
])

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入组名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入组代码', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_-]*$/,
      message: '组代码必须以字母开头，只能包含字母、数字、下划线和连字符',
      trigger: 'blur'
    }
  ],
  environment: [
    { required: true, message: '请选择环境', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择组类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 模拟数据
const mockData: HostGroup[] = [
  {
    id: 'HG001',
    name: 'Web服务器组',
    code: 'web-servers',
    environment: 'prod',
    type: 'web',
    status: 'normal',
    hostCount: 5,
    loadBalancer: {
      enabled: true,
      algorithm: 'round_robin',
      port: 80
    },
    healthCheck: {
      enabled: true,
      interval: 30,
      timeout: 5,
      failureThreshold: 3,
      path: '/health'
    },
    description: '生产环境Web服务器组，负责处理前端请求',
    createTime: '2024-01-15 10:00:00'
  },
  {
    id: 'HG002',
    name: '数据库服务器组',
    code: 'db-servers',
    environment: 'prod',
    type: 'database',
    status: 'normal',
    hostCount: 3,
    loadBalancer: {
      enabled: false,
      algorithm: 'round_robin',
      port: 3306
    },
    healthCheck: {
      enabled: true,
      interval: 60,
      timeout: 10,
      failureThreshold: 2,
      path: '/ping'
    },
    description: '生产环境数据库服务器组，MySQL主从架构',
    createTime: '2024-01-12 14:30:00'
  },
  {
    id: 'HG003',
    name: '缓存服务器组',
    code: 'cache-servers',
    environment: 'test',
    type: 'cache',
    status: 'maintenance',
    hostCount: 2,
    loadBalancer: {
      enabled: true,
      algorithm: 'least_connections',
      port: 6379
    },
    healthCheck: {
      enabled: true,
      interval: 15,
      timeout: 3,
      failureThreshold: 5,
      path: '/ping'
    },
    description: '测试环境Redis缓存服务器组',
    createTime: '2024-01-08 09:15:00'
  }
]

// 获取环境标签类型
const getEnvironmentTagType = (env: string) => {
  const typeMap: Record<string, string> = {
    dev: 'info',
    test: 'warning',
    prod: 'danger'
  }
  return typeMap[env] || 'info'
}

// 获取环境名称
const getEnvironmentName = (env: string) => {
  const option = environmentOptions.value.find(item => item.code === env)
  return option?.name || env
}

// 获取组类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    web: 'primary',
    database: 'success',
    cache: 'warning',
    mq: 'info',
    file: 'primary',
    monitor: 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取组类型标签文本
const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    web: 'Web服务器组',
    database: '数据库服务器组',
    cache: '缓存服务器组',
    mq: '消息队列组',
    file: '文件服务器组',
    monitor: '监控服务器组'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    normal: 'success',
    maintenance: 'warning',
    disabled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    normal: '正常',
    maintenance: '维护中',
    disabled: '停用'
  }
  return statusMap[status] || status
}

// 获取主机组列表
const fetchHostGroupList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    // 应用搜索过滤
    let filteredData = [...mockData]
    if (searchForm.name) {
      filteredData = filteredData.filter(item =>
        item.name.includes(searchForm.name) || item.code.includes(searchForm.name)
      )
    }
    if (searchForm.environment) {
      filteredData = filteredData.filter(item => item.environment === searchForm.environment)
    }
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }

    pagination.total = filteredData.length
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    hostGroupList.value = filteredData.slice(start, end)
  } catch (error) {
    ElMessage.error('获取主机组列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchHostGroupList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    environment: '',
    status: ''
  })
  pagination.currentPage = 1
  fetchHostGroupList()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchHostGroupList()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchHostGroupList()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加主机组'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row: HostGroup) => {
  dialogTitle.value = '编辑主机组'
  isEdit.value = true
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 显示详情对话框
const showDetailDialog = (row: HostGroup) => {
  currentHostGroup.value = row
  detailDialogVisible.value = true
}

// 显示主机列表
const showHostList = (row: HostGroup) => {
  ElMessage.info(`查看主机组 "${row.name}" 的主机列表`)
  // 这里可以跳转到主机列表页面，并过滤该主机组的主机
}

// 管理主机
const manageHosts = (row: HostGroup) => {
  ElMessage.info(`管理主机组 "${row.name}" 的主机`)
  // 这里可以打开主机管理对话框
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: '',
    name: '',
    code: '',
    environment: '',
    type: '',
    status: 'normal',
    hostCount: 0,
    loadBalancer: {
      enabled: false,
      algorithm: 'round_robin',
      port: 80
    },
    healthCheck: {
      enabled: false,
      interval: 30,
      timeout: 5,
      failureThreshold: 3,
      path: '/health'
    },
    description: '',
    createTime: ''
  })
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        ElMessage.success(`${isEdit.value ? '更新' : '创建'}成功`)
        dialogVisible.value = false
        fetchHostGroupList()
      } catch (error) {
        ElMessage.error(`${isEdit.value ? '更新' : '创建'}失败`)
      }
    }
  })
}

// 负载均衡开关变化
const handleLoadBalancerChange = async (row: HostGroup) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))

    const action = row.loadBalancer.enabled ? '启用' : '禁用'
    ElMessage.success(`${action}负载均衡成功`)
  } catch (error) {
    // 回滚状态
    row.loadBalancer.enabled = !row.loadBalancer.enabled
    ElMessage.error('操作失败')
  }
}

// 健康检查开关变化
const handleHealthCheckChange = async (row: HostGroup) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))

    const action = row.healthCheck.enabled ? '启用' : '禁用'
    ElMessage.success(`${action}健康检查成功`)
  } catch (error) {
    // 回滚状态
    row.healthCheck.enabled = !row.healthCheck.enabled
    ElMessage.error('操作失败')
  }
}

// 删除主机组
const handleDelete = async (row: HostGroup) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除主机组 "${row.name}" 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    ElMessage.success('删除成功')
    fetchHostGroupList()
  } catch (error) {
    // 用户取消操作
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchHostGroupList()
})
</script>

<style scoped>
.host-group-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.02);
  border-radius: 8px;
  border: 1px solid rgba(120, 220, 255, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.detail-content {
  padding: 10px 0;
}

.detail-content h4 {
  margin: 20px 0 10px 0;
  color: var(--tech-text-primary);
  font-weight: 600;
}
</style>
